//
//  HJJCircleView.m
//  demo
//
//  Created by hejingjin on 15/9/10.
//  Copyright (c) 2015年 hejingjin. All rights reserved.
//

#import "HJJCircleView.h"
#import "UIImageView+WebCache.h"
@interface HJJCircleView()<UIScrollViewDelegate>{
    NSInteger       _imageIndexFlag;  // 标记当前显示的图片下标
    NSTimer        *_timer;           // 定时器
    NSMutableArray *_imageDataArray;  // 图片数据资源
    NSMutableArray *_imageViews;      // 视图数组
    NSMutableArray *_images;
    NSInteger      imagecount;
    UIPageControl  *_pageControl;     // 分页指示器
}
@property (nonatomic, strong)UIScrollView *scrollView;
/**
 *  初始化数据源
 *
 *  @param imageDataArray 图片数据资源
 */
- (void)initializedDataSourceWithImageDataArray:(NSArray *)imageDataArray;

/**
 *  初始化用户界面
 */
- (void)initializeUserInterface;

/**
 *  插入图片
 */
- (void)insertImageInImageView;
@end


@implementation HJJCircleView

#define HJJ_PICTURESSHOW_WIDTH self.bounds.size.width
#define HJJ_PICTURESSHOW_HEIGHT self.bounds.size.height
#define HJJ_PICTURESSHOW_IMAGEDATA_COUNT _imageDataArray.count




- (instancetype)initWithFrame:(CGRect)frame imageDataArray:(NSArray *)imageDataArray
{
    self = [super initWithFrame:frame];
    if (self) {
        [self initializedDataSourceWithImageDataArray:imageDataArray];
        [self initializeUserInterface];
    }
    return self;
}

#pragma mark - init
- (void)initializedDataSourceWithImageDataArray:(NSArray *)imageDataArray
{
    _imageIndexFlag = 0;
    _imageViews     = [[NSMutableArray alloc] init];
    _imageDataArray = [[NSMutableArray alloc] initWithArray:imageDataArray];

    
}


-(void)setImageDataarray:(NSMutableArray *)imageDataarray{
//    _timer =nil;
    _imageDataarray = imageDataarray;
//    _imagecount
    
//    [_imageDataarray addObject:imageDataarray[0]];
    
    
    [self initializedDataSourceWithImageDataArray:imageDataarray];
    [self initializeUserInterface];
}

- (void)initializeUserInterface
{
//    self.contentMode = UIViewContentModeScaleAspectFill;
    
    // 背景视图
    UIView *backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, HJJ_PICTURESSHOW_WIDTH, HJJ_PICTURESSHOW_HEIGHT)];
    backgroundView.backgroundColor = [UIColor whiteColor];
    [self addSubview:backgroundView];
    
    // 滚动视图
    self.scrollView = ({
        UIScrollView *scrollView = [[UIScrollView alloc] init];
        scrollView.bounds = CGRectMake(0, 0, HJJ_PICTURESSHOW_WIDTH, HJJ_PICTURESSHOW_HEIGHT);
        scrollView.center = CGPointMake(HJJ_PICTURESSHOW_WIDTH / 2, HJJ_PICTURESSHOW_HEIGHT / 2);
        scrollView.contentSize = CGSizeMake(HJJ_PICTURESSHOW_IMAGEDATA_COUNT *HJJ_PICTURESSHOW_WIDTH, HJJ_PICTURESSHOW_HEIGHT);
        if (HJJ_PICTURESSHOW_IMAGEDATA_COUNT == 1) {
            scrollView.contentOffset = CGPointMake(0, 0);
        }else{
             scrollView.contentOffset = CGPointMake(HJJ_PICTURESSHOW_WIDTH, 0);
        }
       
        scrollView.pagingEnabled = YES;
        scrollView.delegate = self;
        scrollView.backgroundColor = [UIColor whiteColor];
        scrollView.bounces = NO;
        scrollView.showsHorizontalScrollIndicator = NO;
        [backgroundView addSubview:scrollView];
        scrollView;
    });
    
    // 添加图片视图
    for (int i = 0; i < HJJ_PICTURESSHOW_IMAGEDATA_COUNT; i++) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i *HJJ_PICTURESSHOW_WIDTH, 0, HJJ_PICTURESSHOW_WIDTH, HJJ_PICTURESSHOW_HEIGHT)];
//        imageView.contentMode = UIViewContentModeScaleAspectFit;
        
        imageView.userInteractionEnabled = YES;
        imageView.backgroundColor = [UIColor whiteColor];
        // 添加点击图片视图手势
        UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureRecognizerPressed:)];
        [imageView addGestureRecognizer:tapGestureRecognizer];
        [_scrollView addSubview:imageView];
        [_imageViews addObject:imageView];
        
    }
    
    // 添加图片
    [self insertImageInImageView];
    
    // 分页指示器
    _pageControl = [[UIPageControl alloc] init];
    _pageControl.bounds = CGRectMake(0, 0, HJJ_PICTURESSHOW_WIDTH, 30);
    _pageControl.center = CGPointMake(HJJ_PICTURESSHOW_WIDTH / 2, HJJ_PICTURESSHOW_HEIGHT - CGRectGetMidY(_pageControl.bounds));
    _pageControl.numberOfPages = HJJ_PICTURESSHOW_IMAGEDATA_COUNT;
    _pageControl.userInteractionEnabled = NO;
    _pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
    _pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];
    [self addSubview:_pageControl];
    [self bringSubviewToFront:_pageControl];
    
    // 定时器
    _timer = [NSTimer scheduledTimerWithTimeInterval:3.50f target:self selector:@selector(processTimer) userInfo:nil repeats:HUGE_VAL];
    
    
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    
    _timer.fireDate = [[NSDate date] dateByAddingTimeInterval:3.50f];
    
    if (HJJ_PICTURESSHOW_IMAGEDATA_COUNT == 1) {
        [self invalidateTimer];
        _pageControl.hidden = YES;
    }
  
}

#pragma mark - other methods

- (void)insertImageInImageView
{
    // 逻辑判断
    if (_imageViews.count <= 0) {
        return;
    }
    
    
    NSInteger index = 0;
    for (UIImageView *imageView in _imageViews) {
//        imageView.contentMode = UIViewContentModeScaleAspectFill;
        if ([_imageDataArray[index] isKindOfClass:[NSString class]] && [_imageDataArray[index] hasPrefix:@"http://"]) {
            [imageView sd_setImageWithURL:[NSURL URLWithString:_imageDataArray[index]] placeholderImage:[UIImage imageNamed:@"banner"]];
//            [imageView sd_setImageWithURL:[NSURL URLWithString:_imageDataArray[index]]];
        }else{
            imageView.image = [UIImage imageNamed:_imageDataArray[index]];
        }
        index ++;
    }
}

#pragma mark - <UIScrollViewDelegate>

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.x >= 2* HJJ_PICTURESSHOW_WIDTH) {
        // 向左滑动
        id firstImageData = [_imageDataArray.firstObject mutableCopy];
        [_imageDataArray removeObjectAtIndex:0];
        [_imageDataArray addObject:firstImageData];
        // 指示器
        _pageControl.currentPage = _pageControl.currentPage == HJJ_PICTURESSHOW_IMAGEDATA_COUNT - 1 ? 0 : _pageControl.currentPage + 1;
        // 标记
        _imageIndexFlag = _imageIndexFlag == HJJ_PICTURESSHOW_IMAGEDATA_COUNT - 1 ? 0 : _imageIndexFlag + 1;
    }else if (scrollView.contentOffset.x <= 0){
        // 向右滑动
        id lastImageData = [_imageDataArray.lastObject mutableCopy];
        [_imageDataArray removeLastObject];
        [_imageDataArray insertObject:lastImageData atIndex:0];
        // 分页控件
        _pageControl.currentPage = _pageControl.currentPage == 0 ? HJJ_PICTURESSHOW_IMAGEDATA_COUNT - 1 : _pageControl.currentPage - 1;
        // 标记
        _imageIndexFlag = _imageIndexFlag == 0 ? HJJ_PICTURESSHOW_IMAGEDATA_COUNT - 1 : _imageIndexFlag - 1;
    }else{
        // 停在中间
        
        return;
    }
    
    [self insertImageInImageView];
    scrollView.contentOffset = CGPointMake(HJJ_PICTURESSHOW_WIDTH, 0);
    
//    if (HJJ_PICTURESSHOW_IMAGEDATA_COUNT < 3) {
//        scrollView.contentOffset =CGPointMake(HJJ_PICTURESSHOW_WIDTH, 0);
//
//    }else{
//        scrollView.contentOffset = CGPointMake(HJJ_PICTURESSHOW_WIDTH, 0);
//    }
    
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self pauseTimer];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self startTimer];
}

#pragma mark - tapGesture pressed

/**
 *  图片视图点击手势处理,当用户点击图片的时候会返回一个图片下标标记用户当前选中的是哪一项,并做出相应的界面推送处理
 *
 *  @param tapGesture 点击手势
 */
- (void)tapGestureRecognizerPressed:(UITapGestureRecognizer *)tapGesture
{
    // 代理人执行协议方法,将图片下标传送出去
    [self.delegate HJJCircleViewImageWithImageIndexFlag:self.imageIndexFlag circleview:self];
}

#pragma mark - timer pressed

- (void)processTimer
{
    if(HJJ_PICTURESSHOW_IMAGEDATA_COUNT < 3){
            [_scrollView setContentOffset:CGPointMake(0 *HJJ_PICTURESSHOW_WIDTH, 0) animated:YES];
        }else{
            [_scrollView setContentOffset:CGPointMake(2 *HJJ_PICTURESSHOW_WIDTH, 0) animated:YES];
        }
  
}

- (void)startTimer
{
    _timer.fireDate = [NSDate dateWithTimeIntervalSinceNow:3.5];
}

- (void)pauseTimer
{
    _timer.fireDate = [NSDate distantFuture];
}

- (void)invalidateTimer
{
    [_timer invalidate];
}

@end
